package com.aegis.gateway.filter;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotPermissionException;
import com.aegis.common.exception.AuthorizationException;
import com.aegis.common.web.BaseResponseEnum;
import com.aegis.common.web.ResultUtil;
import com.aegis.common.web.WebResponse;
import com.aegis.gateway.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube order: -100
 */
@Component
@Slf4j
public class SaFilterErrorStrategy implements cn.dev33.satoken.filter.SaFilterErrorStrategy {
    @Override
    public Object run(Throwable e) {
        log.info("WxSaFilterErrorStrategy handle error");
        log.info("method : {}", SaHolder.getRequest().getMethod());
//                    log.info("header token: {}", SaHolder.getRequest().getHeader(saTokenConfig.getTokenName()));
        log.info("url: {}", SaHolder.getRequest().getUrl());
        log.error("异常详情", e);
        SaHolder.getResponse().setHeader("Content-Type", "application/json;charset=UTF-8");
        WebResponse<?> response = null;
        if (e instanceof NotPermissionException) {
            log.info("用户尝试越权访问 id: {}", AuthUtil.getUserId());
            SaHolder.getResponse().setStatus(403);
            response = ResultUtil.genFailResult(BaseResponseEnum.NO_PERMISSION, e.getMessage());
            log.info("权限拦截响应01 {}", response);
            return response;
        } else if (e instanceof AuthorizationException) {
            SaHolder.getResponse().setStatus(401);
            response = ResultUtil.genFailResult(BaseResponseEnum.UNAUTHORIZED, e.getMessage());
            log.info("权限拦截响应02 {}", response);
        } else {
            SaHolder.getResponse().setStatus(500);
            response = ResultUtil.genFailResult(BaseResponseEnum.OPERATE_FAIL);
            log.info("权限拦截响应03 {}", response);
        }
        return response;
    }
}
